import {Component} from '@angular/core';
import { IonicPage,NavController, NavParams, ToastController} from 'ionic-angular';
// import { MystatePage } from '../mystate/mystate';
import {GetVideoDetailService} from "../../service/http-service/getVideoDetail.service";
import {ApplicantService} from "../../service/http-service/applicant.service";
import { CommonHttpService } from '../../service/http-service/common/common-http-service';
// import {VgAPI} from "videogular2/core";
import {UsrLogin} from "../../service/http-service/usrLogin.service";
import { BrowserInterceptor } from '../../service/http-service/browser-interceptor';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import {PostwatchednumService} from "../../service/http-service/postwatchednum.service";
// import {PhonePage} from "../phone/phone";
// import {HomePage} from "../home/home";



/**
 * Generated class for the ListvidoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

 @IonicPage()
@Component({
  selector: 'page-watchvideo',
  templateUrl: 'watchvideo.html',

})
export class WatchvideoPage{

  video={"img": "", "name": "", "type": "", "depict": "","id":1,"url":"","duration":""};
  // video={"id": "", "userid": "", "username": "", "commidityId": "","comment":""};
  comment_list: Array<{id: string, userid: string, username: string, commidityId: string,comment:string ,ifThumbsUp:boolean,gmtCreate:number}>;
  videoID: string;
  comment={"size":""};
  toastCtrl:ToastController;

  token: any;
  openid:any;
  guanZhu: any;

  timeStamp2: number;
  authenSign : any;
  average_score: any;
  // duration : any;
  duration1: any;
  v: any;
  // videoUrl: any;
  huibenId: string;
  // sources : Array<Object>;
  // api:VgAPI;
  constructor(public iab:InAppBrowser,public postwatchednum: PostwatchednumService, public navCtrl: NavController,private bint :BrowserInterceptor,private usrLogin: UsrLogin, public navParams: NavParams,public getVideoDetailservice:GetVideoDetailService,public  applicationService:ApplicantService,public toastService:ToastController,public commonHttp: CommonHttpService) {
    this.huibenId= window.location.search;
    // this.videoUrl = navParams.get("Url")
    // console.log("dddddddddddddd");
    // console.log(this.videoID);
    // console.log(this.videoUrl);

    this.toastCtrl=toastService;


  }


  ionViewDidLoad(){



    var dev = false;//dev true:测试环境 false:线上环境

    //
    if(dev){
      let options1 = {"id":11,"realname":null,"gender":0,"age":null,"phone":13910296297,"openid":"otjnQwZG7qciTi-K21SmWkN-1VB8","password":null,"header_img":"http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIEHafTGHpmIGJLSUrg7RuXXrN3wGezFgfbLXUbKIBLy63YflqKSgTE1cT6BeUmQQEP0oBertquqA/0","gmtCreate":1513915509000,"gmtModified":1513915509000,"username":"李德","token":"Bear_eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMSIsImlhdCI6MTUyNjAxODA5MCwic3ViIjoie1wiaWRcIjoxMSxcIm9wZW5pZFwiOlwib3RqblF3Wkc3cWNpVGktSzIxU21Xa04tMVZCOFwifSIsImlzcyI6Imh1aXpoaWhhbmxpbiIsImV4cCI6MTUyNjYyMjg5MH0.8V-MSbQ3g7djG6P1njbYyAwGi_HnpD7RLBmZF936OSMmAlschc","role":{"id":11,"auth":null,"name":null,"permis":null,"gmtCreate":1513915509000,"gmtModified":1513915509000},"realName":null}

      localStorage.setItem('options', JSON.stringify(options1));

      this.token = localStorage.setItem('token',JSON.parse(localStorage.getItem('options')).token);

    }else{
      let useragent = navigator.userAgent;
      this.bint.browserBlock(useragent);


      this.usrLogin.authenJudge()

    }
    this.getVideoDetail();



   this.getSubscribe();

  }




  /*
       +  * 上传视频观看次数
       +  * */
  postWatchedNum() {
    this.videoID = this.GetQueryString('vid')
    this.postwatchednum.postWatchedNum(this.videoID).subscribe(resp => {
      if (resp.data !== null && resp.code == 200) {
        console.log("观看视频次数：" + resp.data);
      }
    }, error2 => {
      console.log(error2);
    });}


    // authenJudge(){
    //   this.timeStamp2 = Number(localStorage.getItem("timeStamp2"));
    //   // console.log("this.timeStamp0");
    //   // console.log(this.timeStamp1);
    //   this.token = localStorage.getItem("token");
    //   // console.log("this.timeStamp0");
    //   // console.log(this.timeStamp1);
    //   console.log(this.timeStamp2!=null&&this.timeStamp2!=undefined&&this.timeStamp2!=0);
    //
    //   if(this.token==null||this.token==undefined){
    //     this.authenSign=true;
    //   } else {
    //
    //     if (this.timeStamp2 != null && this.timeStamp2 != undefined && this.timeStamp2 != 0) {
    //       this.timeStamp2 = Math.floor(((new Date().getTime()) - this.timeStamp2) / (24 * 3600 * 1000));
    //       if (this.timeStamp2 >= 10 || this.timeStamp2 == NaN || this.timeStamp2 < 0) {
    //
    //         this.authenSign = true;
    //       } else {
    //
    //         this.authenSign = false;
    //         this.applicationService.freshTokenn();
    //
    //       }
    //
    //     } else {
    //
    //       this.authenSign = true
    //     }
    //   }
    //
    //   if(this.authenSign==true){
    //     console.log("this.timeStamp4")
    //     //   console.log(this.authenSign);
    //     // this.number1=Number(localStorage.getItem("aaaa"));
    //     // this.number1++;
    //     //  console.log(this.number1);
    //     // localStorage.setItem("aaaa",this.number1);
    //     //  if(this.number1<2){}
    //     this.usrLogin.goAuth();
    //
    //   }
    // }



    /**
   * 获取视频详情
   */



  getVideoDetail(){
    this.getVideoDetailservice.getHuibenDetail(this.huibenId).subscribe(resp=>{
      if (resp.data!==null&& resp.code==200){
        this.video=resp.data;
        this.average_score = Math.floor(resp.data.average_score * 10 + 0.5) / 10;
        this.duration1=this.video.duration.substr(3,5);
        console.log(this.video.url)

        // var sUserAgent = navigator.userAgent.toLowerCase();
        // var rr= sUserAgent.match(/iphone os/i);
        //
        // if(rr== null||rr==undefined) {
        //   this.v = document.getElementsByTagName("video")[0];
        //
        //   this.v.src = this.video.url;
        //   this.v.addEventListener("seeked", function (e) {
        //     this.v.play();
        //   }, false);

        // }
        this.androidVideo();
          this.postWatchedNum();

      }else if(resp.data!==null &&resp.code==1401){
        this.applicationService.freshTokenn();
       // this.getVideoDetail();
      }
    },error2 => {

      console.log(error2);
    });
  }

  androidVideo() {

    // var sUserAgent = navigator.userAgent.toLowerCase();
    // var bIsIphoneOs = sUserAgent.match(/iphone os/i);
    // if (bIsIphoneOs == null || bIsIphoneOs == undefined) {
      this.v = document.getElementsByTagName("video")[0];
      if(this.v){

      this.v.src = this.video.url;
      this.v.addEventListener("seeked", function () {
        this.v.play();
       }, false);
      }
  }

  applePlay(){

    this.iab.create(this.video.url, '_self', {location: "yes"});


  }

  /**
   * 获取关注状态
   */

  getSubscribe(){

    this.getVideoDetailservice.getIsSubscribe().subscribe(resp=>{

    console.log(resp.data);
    if(resp.data){
      this.guanZhu = "首页"
    } else { this.guanZhu = "关注"}

      },error3=>{console.log(error3)

    });

  }


  watchPcenter(){


    if (this.guanZhu =="首页") {
      this.v = document.getElementsByTagName("video")[0];

      this.v.pause();

      this.navCtrl.push('HomePage');
      // this.navCtrl.remove(-1);

    } else if(this.guanZhu=="关注") {
      let urlLogin="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1MTY0ODk1MA==&scene=110#wechat_redirect";
      this.iab.create(urlLogin, '_self', {location: "yes"});
    }erro4=>{ console.log(erro4)};

  }

  GetQueryString(name)
  {
    var reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)");
    var r= window.location.search.substr(1).match(reg);
    // this.vid1 = '?code=071zrjxT173Yg81otkyT1f6oxT1zrjxy&state=1';
    // var r = this.r.substr(1).match(reg);
    if(r!=null)return  decodeURIComponent(r[2]); return null;
  }


}
